package org.richin.servlet.Filter.util;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class SubChain implements FilterChain {
	private final FilterChain parent;
	private final List<Filter> filters;
	private RequestDispatcher forward;

	private int pointer = 0;

	public SubChain(FilterChain parent, List<Filter> filters) {
		this.filters = filters;
		this.parent = parent;
	}

	public void setForward(RequestDispatcher forward) {
		this.forward = forward;
	}

	public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
		if (pointer == filters.size()) {
			if (forward != null)
				forward.forward(request, response);
			else
				parent.doFilter(request, response);
		} else {
			filters.get(pointer++).doFilter(request, response, this);
		}
	}

}
